#include "RealtimePositionWindow.h"
#include "ui_RealtimePositionWindow.h"

RealtimePositionWindow::RealtimePositionWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::RealtimePositionWindow)
{
    ui->setupUi(this);

    // 初始化实时位置显示场景
    positionScene = new QGraphicsScene(this);
    ui->positionView->setScene(positionScene);

    // 初始化TCP服务器
    tcpServer = new QTcpServer(this);
    if (!tcpServer->listen(QHostAddress::Any, 54321)) {
        ui->statusLabel->setText("Error: Could not start server.");
        return;
    }

    connect(tcpServer, &QTcpServer::newConnection, this, &RealtimePositionWindow::onNewConnection);

    // 添加连接按钮
//    QPushButton* connectButton = new QPushButton(this);
//    //    ui->centralWidget->layout()->addWidget(connectButton);
//    connect(connectButton, &QPushButton::clicked, this, &RealtimePositionWindow::onConnectButtonClicked);
}

RealtimePositionWindow::~RealtimePositionWindow() {
    tcpServer->close();
    delete ui;
}

void RealtimePositionWindow::onNewConnection() {
    QTcpSocket* clientSocket = tcpServer->nextPendingConnection();
    connect(clientSocket, &QTcpSocket::readyRead, this, &RealtimePositionWindow::onReadPosition);
}
void RealtimePositionWindow::onReadPosition() {
    QTcpSocket* clientSocket = qobject_cast<QTcpSocket*>(sender());
    if (!clientSocket) return;

    QString message = QString::fromUtf8(clientSocket->readLine()).trimmed();
    if (message.startsWith("INITIAL_POINT")) {
        QStringList parts = message.split(' ');
        if (parts.size() == 3) {
            qreal x = parts[1].toDouble();
            qreal y = parts[2].toDouble();
            initialPoint = QPointF(x, y);

            // 绘制初始点
            positionScene->addEllipse(initialPoint.x() - 2, initialPoint.y() - 2, 4, 4, QPen(Qt::red), QBrush(Qt::red));
        }
    } else if (message.startsWith("TRACK_POINT")) {
        QStringList parts = message.split(' ');
        if (parts.size() == 3) {
            qreal x = parts[1].toDouble();
            qreal y = parts[2].toDouble();
            QPointF point(x, y);

            // 绘制轨迹点
            positionScene->addEllipse(point.x() - 2, point.y() - 2, 4, 4, QPen(Qt::red), QBrush(Qt::red));

            // 如果有前一个点，绘制连接线
            if (!trackPoints.isEmpty()) {
                QPointF lastPoint = trackPoints.last();
                positionScene->addLine(lastPoint.x(), lastPoint.y(), point.x(), point.y(), QPen(Qt::red, 2));
            }

            trackPoints.append(point);  // 将新点添加到轨迹列表
        }
    }
}

void RealtimePositionWindow::onConnectButtonClicked() {
    // 发送初始点请求到 AUVMainWindow
    QTcpSocket* clientSocket = tcpServer->nextPendingConnection();
    if (clientSocket) {
        connect(clientSocket, &QTcpSocket::readyRead, this, &RealtimePositionWindow::onReadPosition);
        clientSocket->write("REQUEST_INITIAL_POINT\n");
    }
}
